package com.nui.multiphotopicker.view;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import xf.tools.Other;
import android.app.ActionBar.LayoutParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.emm.yixun.mobile.R;
import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.base.BaseActivity;
import com.nui.multiphotopicker.adapter.ImageGridAdapter;
import com.nui.multiphotopicker.adapter.ImagePublishAdapter;
import com.nui.multiphotopicker.model.ImageItem;
import com.nui.multiphotopicker.util.CustomConstants;
import com.nui.multiphotopicker.util.IntentConstants;
import com.vgo.crop.view.Crop_Activity;

/**
 * 
 * <p>
 * <b>Title：</b> 图片选择
 * </p>
 * <p>
 * <b>Description：</b>
 * </p>
 * 
 * @author tangxin
 * @date 2016年12月6日 下午3:46:35
 */
public class ImageChooseActivity extends BaseActivity {

	/** 相册中图片对象集合 */
	private List<ImageItem> mDataList = new ArrayList<ImageItem>();

	/** 相册名称 */
	private String mBucketName;

	/** 单次最多发送图片数 */
	private int availableSize;

	private GridView mGridView, gridview_two;

	/** 标题 */
	private TextView mBucketNameTv;

	/** 返回键 */
	private TextView cancelTv;

	/** 相册适配器 */
	private ImageGridAdapter mAdapter;

	private Button mFinishBtn;

	/** key为imageId value为ImageItem */
	private HashMap<String, ImageItem> selectedImgs = new HashMap<String, ImageItem>();

	private ImagePublishAdapter mAdapter_two;

	/** 删除图片弹出框 */
	private PopupWindow exit_poPopupWindow;

	private View view;

	private int mposition;

	List<ImageItem> mDataList_two = null;

	/** 图片对象 */
	ImageItem item;

	private File mTempDir;

	ImageView phone_back_te;

	/** 确定按钮 */
	TextView is_sure_title;

	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.act_image_choose);
		BaseActivity.activity = this;

		mDataList = (List<ImageItem>) getIntent().getSerializableExtra(IntentConstants.EXTRA_IMAGE_LIST);
		if (mDataList == null) {
			mDataList = new ArrayList<ImageItem>();
		}

		mBucketName = getIntent().getStringExtra(IntentConstants.EXTRA_BUCKET_NAME);
		if (TextUtils.isEmpty(mBucketName)) {
			mBucketName = "请选择";
		}

		availableSize = getIntent().getIntExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE,
				CustomConstants.MAX_IMAGE_SIZE);

		is_sure_title = (TextView) findViewById(R.id.is_sure_title);
		is_sure_title.setVisibility(EmmApplication.IsMoreSelect == true ? View.VISIBLE : View.GONE);

		if (EmmApplication.IsMoreSelect) {
			for (int u = 0; u < EmmApplication.pir.size(); u++) {
				for (int i = 0; i < mDataList.size(); i++) {
					if (EmmApplication.pir.get(u).imageId.equals(mDataList.get(i).imageId)) {
						mDataList.get(i).isSelected = EmmApplication.pir.get(u).isSelected;
					}
				}
			}
		}

		phone_back_te = (ImageView) findViewById(R.id.title_bar).findViewById(R.id.phone_back_te);
		phone_back_te.setVisibility(View.GONE);
		phone_back_te.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), ImageBucketChooseActivity.class);
				startActivity(intent);
				finish();
			}
		});

		initView();
		initListener();
		showPopupWindow2();
		mTempDir = new File(Environment.getExternalStorageDirectory(), "Temp");
		if (!mTempDir.exists()) {
			mTempDir.mkdirs();
		}

		is_sure_title.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				selectedImgs = new HashMap<String, ImageItem>();
				for (int r = 0; r < mDataList.size(); r++) {
					if (mDataList.get(r).isSelected) {
						selectedImgs.put(mDataList.get(r).imageId, mDataList.get(r));
					}
				}

				lp = (List<ImageItem>) new ArrayList<ImageItem>(selectedImgs.values());
				try {
					if (null == lp || lp.size() <= 0) {
						EmmApplication.T("还没选择照片");
						return;
					}
				} catch (IndexOutOfBoundsException e) {
				}
				EmmApplication.pir.addAll(lp);
				removeDuplicate(EmmApplication.pir);
				sendBroadcast(new Intent(Other.VGOPLAY_1));
				sendBroadcast(new Intent(EmmApplication.SendBroadcastContent));// 通知跟进界面准备发送图片
				finish();
			}
		});

	}

	/**
	 * 去重
	 * 
	 * @param list
	 * @return
	 */
	public static List<ImageItem> removeDuplicate(List<ImageItem> list) {
		List<ImageItem> list2 = list;
		for (int i = 0; i < list.size(); i++) {
			ImageItem item = list.get(i);
			int h = 0;
			for (int y = 0; y < list2.size(); y++) {
				if (item.imageId.equals(list2.get(y).imageId)) {
					h++;
					if (h > 1) {
						list2.get(y).sourcePath = "1101841323";
					}
				} else {
				}
			}
		}
		Iterator<ImageItem> iter = list2.iterator();
		while (iter.hasNext()) {
			ImageItem element = iter.next();
			if ("1101841323".equals(element.sourcePath))
				iter.remove();
		}

		return list2;
	}

	protected void onResume() {
		BaseActivity.activity = this;
		IntentFilter filter = new IntentFilter(Other.VGOPLAY_1);
		registerReceiver(mBroadcastReceiver, filter);
		super.onResume();
	};

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Other.VGOPLAY_1)) {
				finish();
			}
		}
	};

	protected void onDestroy() {
		unregisterReceiver(mBroadcastReceiver);
		super.onDestroy();
	};

	private void initView() {
		mBucketNameTv = (TextView) findViewById(R.id.title);
		mBucketNameTv.setText(mBucketName);

		mGridView = (GridView) findViewById(R.id.gridview);
		gridview_two = (GridView) findViewById(R.id.gridview_two);

		mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		mAdapter = new ImageGridAdapter(ImageChooseActivity.this, mDataList);
		mGridView.setAdapter(mAdapter);
		mFinishBtn = (Button) findViewById(R.id.finish_btn);
		cancelTv = (TextView) findViewById(R.id.action);

		SetRelativiLayoutPadding(R.id.main_head_top_rela_header);

		mAdapter.notifyDataSetChanged();
	}

	public static List<ImageItem> lp;

	private void initListener() {
		mFinishBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				lp = (List<ImageItem>) new ArrayList<ImageItem>(selectedImgs.values());
				if ("1".equals(EmmApplication.getData("Picture"))) {
					try {
						if (null == lp || lp.size() <= 0) {
							EmmApplication.T("你还没选择照片");
							return;
						}
						Intent intent = new Intent(ImageChooseActivity.this, Crop_Activity.class);
						startActivity(intent);
						EmmApplication.setData("Photograph_uri", lp.get(0).sourcePath);
						Other.Photograph_uri = lp.get(0).sourcePath;
					} catch (IndexOutOfBoundsException e) {
					}
				} else {

					Intent intent = new Intent(Other.IMAGEITEM);
					sendBroadcast(intent);
				}

				finish();
			}

		});

		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				mDataList_two = new ArrayList<ImageItem>();
				item = mDataList.get(position);
				if (!EmmApplication.IsMoreSelect) {
					Intent intent = new Intent(ImageChooseActivity.this, Crop_Activity.class);
					startActivity(intent);
					EmmApplication.setData("Photograph_uri", item.sourcePath);
					Other.Photograph_uri = item.sourcePath;
				} else {// 多选
					if (item.isSelected) {
						item.isSelected = false;
						selectedImgs.remove(item.imageId);
						if (EmmApplication.IsMoreSelect) {
							for (int i = 0; i < EmmApplication.pir.size(); i++) {
								if (EmmApplication.pir.get(i).imageId.equals(item.imageId)) {
									EmmApplication.pir.remove(i);
									break;
								}
							}
						}
						mDataList_two.addAll(new ArrayList<ImageItem>(selectedImgs.values()));
						mAdapter_two = new ImagePublishAdapter(ImageChooseActivity.this, mDataList_two, 2);
						gridview_two.setAdapter(mAdapter_two);
					} else {
						if ("1".equals(EmmApplication.getData("Picture"))) {
							if (selectedImgs.size() >= EmmApplication.SelectNumber) {
								EmmApplication.T("最多选择" + EmmApplication.SelectNumber + "张图片");
								return;
							}
						} else {
							if (selectedImgs.size() >= availableSize) {
								EmmApplication.T("最多选择" + availableSize + "张图片");
								return;
							}
						}
						item.isSelected = true;
						selectedImgs.put(item.imageId, item);
						mDataList_two.addAll(new ArrayList<ImageItem>(selectedImgs.values()));
						mAdapter_two = new ImagePublishAdapter(ImageChooseActivity.this, mDataList_two, 2);
						gridview_two.setAdapter(mAdapter_two);
					}
					mAdapter.notifyDataSetChanged();
					mAdapter_two.notifyDataSetChanged();
				}
			}

		});

		cancelTv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	public void showPopupWindow2() {

		view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.dialog_issure_delete, null);

		exit_poPopupWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		TextView cannel = (TextView) view.findViewById(R.id.issue_sign_cannel);
		TextView sure = (TextView) view.findViewById(R.id.issue_sign_sure);

		cannel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {

				if (exit_poPopupWindow.isShowing()) {
					exit_poPopupWindow.dismiss();
				}
			}
		});

		sure.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {

				mDataList.get(mposition).isSelected = false;
				selectedImgs.remove(mDataList.get(mposition).imageId);
				mDataList.addAll(new ArrayList<ImageItem>(selectedImgs.values()));
				mAdapter = new ImageGridAdapter(ImageChooseActivity.this, mDataList);
				mGridView.setAdapter(mAdapter);
				mAdapter.notifyDataSetChanged();

				System.out.println("" + selectedImgs.size());
				System.out.println("" + mDataList.get(mposition).imageId);

				mDataList_two.remove(mposition);

				mAdapter_two = new ImagePublishAdapter(ImageChooseActivity.this, mDataList_two, 2);

				gridview_two.setAdapter(mAdapter_two);
				mAdapter_two.notifyDataSetChanged();

				for (int i = 0; i < mDataList_two.size(); i++) {
					System.out.println("" + mDataList_two.get(i).sourcePath);
				}

				exit_poPopupWindow.dismiss();
			}
		});
		view.setFocusable(true); // 这个很重要
		exit_poPopupWindow.setFocusable(true);
		exit_poPopupWindow.setOutsideTouchable(true);

		view.setFocusableInTouchMode(true);

		view.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					exit_poPopupWindow.dismiss();
					exit_poPopupWindow = null;
					return true;
				}
				return false;
			}
		});

		view.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stu
				int height = view.findViewById(R.id.popu_boss).getTop();
				int bottom = view.findViewById(R.id.popu_boss).getBottom();
				int y = (int) event.getY();
				if (event.getAction() == MotionEvent.ACTION_UP) {
					if (y < height || y > bottom) {
						exit_poPopupWindow.dismiss();

					}
				}

				return true;
			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			if ("1".equals(EmmApplication.getData("Picture"))) {
				finish();
			} else {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), ImageBucketChooseActivity.class);
				startActivity(intent);

			}

		}
		return super.onKeyDown(keyCode, event);
	}

}